package com.ddz.implementation;

import java.io.IOException;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;

public class Music implements OnCompletionListener, OnSeekCompleteListener,
		OnPreparedListener, OnVideoSizeChangedListener {
	MediaPlayer mMediaPlayer;
	boolean mIsPrepared = false;

	public Music(AssetFileDescriptor assetDescriptor) {
		mMediaPlayer = new MediaPlayer();
		try {
			mMediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(),
					assetDescriptor.getStartOffset(),
					assetDescriptor.getLength());
			mMediaPlayer.prepare();
			mIsPrepared = true;
			mMediaPlayer.setOnCompletionListener(this);
			mMediaPlayer.setOnSeekCompleteListener(this);
			mMediaPlayer.setOnPreparedListener(this);
			mMediaPlayer.setOnVideoSizeChangedListener(this);

		} catch (Exception e) {
			throw new RuntimeException("Couldn't load music");
		}
	}

	public void dispose() {
		if (mMediaPlayer.isPlaying()) {
			mMediaPlayer.stop();
		}
		mMediaPlayer.release();
	}

	public boolean isLooping() {
		return mMediaPlayer.isLooping();
	}

	public boolean isPlaying() {
		return mMediaPlayer.isPlaying();
	}

	public boolean isStopped() {
		return !mIsPrepared;
	}

	public void pause() {
		if (this.mMediaPlayer.isPlaying())
			mMediaPlayer.pause();
	}

	public void play() {
		if (this.mMediaPlayer.isPlaying())
			return;

		try {
			synchronized (this) {
				if (!mIsPrepared)
					mMediaPlayer.prepare();
				mMediaPlayer.start();
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setLooping(boolean isLooping) {
		mMediaPlayer.setLooping(isLooping);
	}

	public void setVolume(float volume) {
		mMediaPlayer.setVolume(volume, volume);
	}

	public void stop() {
		if (this.mMediaPlayer.isPlaying() == true) {
			this.mMediaPlayer.stop();

			synchronized (this) {
				mIsPrepared = false;
			}
		}
	}

	public void onCompletion(MediaPlayer player) {
		synchronized (this) {
			mIsPrepared = false;
		}
	}

	public void seekBegin() {
		mMediaPlayer.seekTo(0);

	}

	@Override
	public void onVideoSizeChanged(MediaPlayer arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPrepared(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		synchronized (this) {
			mIsPrepared = true;
		}
	}

	@Override
	public void onSeekComplete(MediaPlayer arg0) {
		// TODO Auto-generated method stub

	}
}
